<template>
  <el-upload
    class="upload-demo"
    action="null"
    :objId="objId"
    :multiple="multiple"
    :show-file-list="false"
    :before-upload="beforeUpload"
    :http-request="uploadFile"
    :accept="accept"
    :on-success="handleSuccess"
    :on-error="handleError"
  >
    <el-button size="small" slot="trigger"><slot>上传</slot></el-button>
  </el-upload>
</template>

<script>
import { attachmentService } from "@/api/sysService";
export default {
  name: "UploadComponent",
  props: {
    // 业务Id, 回调用端
    objId: {
      type: Number,
      required: true,
    },

    accept: {
      type: String,
      default: ".jpg,.jpeg,.png",
    },
    uploadUrl: {
      type: String,
      required: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    fileList: {
      type: Array,
      default: () => [],
    },
  },
  methods: {
    beforeUpload(file) {
      const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 10; // 500kb限制
      if (!isJPGOrPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 500KB!");
        return false;
      }
      return true; // 如果文件验证通过，则返回true继续上传。
    },

    uploadFile(item) {
      const formData = new FormData();
      formData.append("file", item.file);
      console.log(item.file);
      attachmentService.postUpload(formData).then((res) => {
        this.$emit("uploadSuccess", { ...res.data, objId: this.objId });
      });
    },
    handleSuccess(response, file, fileList) {
      this.$message.success("上传成功");
      // 处理上传成功的逻辑，例如更新fileList等。
    },
    handleError(err, file, fileList) {
      this.$message.error("上传失败");
      // 处理上传失败的逻辑。
    },
  },
};
</script>
